/**
 * service: person
 *
 * @author    Dmitry Ustimov
 * @date      March 2012
 *
 */
package com.gr

class PersonService {
	static transactional = true
		
	def DistributorService

	def getlist(params) {
		println(params)
		def projTo = Project.get(params.get("id"))
		return Person.findAllByProjectToLike(projTo).collect{[
			text : it.name, 
			id   : it.id.toString(), 
			leaf : "true"
		]}
	}
	
	def getElement(params) {
		println(params)
		def el = Person.get(params.get("id"))
		return [
			'success' : 'true', 
			id        : el.id, 
			name      : el.name, 
			email     : el.email, 
			birthDate : el.birthDate, 
			hiredDate : el.hiredDate, 
			projectTo : el.projectTo.title
		]
	}
	
	def addElement(params) {
		println(params)
		def projTo = Project.get(params.get("projectTo"))
		if (projTo) {
			def newPerson = new Person()
			newPerson.name = params.get('name')
			newPerson.email = params.get('email')
			if (params.get('birthDate')) newPerson.birthDate = new Date(params.get('birthDate'))
			if (params.get('hiredDate')) newPerson.hiredDate = new Date(params.get('hiredDate'))
			newPerson.projectTo = projTo
			if (newPerson.save()) {
				return ['success':'true']
			}
			else {
				return ['success':'false']
			}
		}
		else {
			return ['success':'false']
		}
	}
	
	def editElement(params) {
		println(params)
		def projTo = Project.get(params.get("projectTo"))
		if (projTo) {
			def editPerson = Person.get(params.get('id'))
			editPerson.name = params.get('name')
			editPerson.email = params.get('email')
			if (params.get('birthDate')) 
				editPerson.birthDate = new Date(params.get('birthDate'))
			else 
				editPerson.birthDate = null
			if (params.get('hiredDate')) 
				editPerson.hiredDate = new Date(params.get('hiredDate'))
			else 
				editPerson.hiredDate = null
			editPerson.projectTo = projTo
			if (editPerson.save()) {
				return ['success':'true']
			}
			else {
				return ['success':'false']
			}
		}
		else {
			return ['success':'false']
		}
	}
	
	def deleteElement(params) {
		println(params)
		def foundPerson = Person.get(params.get('id'))
		foundPerson.delete()		
		return ['success':'true']
	}
}
